package com.example.xianji.adapter;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources.NotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.xianji.Contant;
import com.example.xianji.XJApplication;
import com.example.xianji.R;
import com.example.xianji.bean.NewsReplay;
import com.example.xianji.bean.ReplayLouZhu;
import com.example.xianji.constant.Constant;
import com.example.xianji.single.Send_Contant;
import com.example.xianji.utils.DownLoadUtils;
import com.example.xianji.utils.DownLoadUtils.OnDownloadListener;
import com.example.xianji.utils.sp.PreferenceEngine;
import com.example.xianji.widgets.CircleImageView;
import com.example.xianji.widgets.MyListview;
import com.example.xianji.eventbus.Replay_EventBus;
import com.nostra13.universalimageloader.core.ImageLoader;

public class Value_Adapter extends BaseAdapter {
    /***************评论一级适配器*********************/
    private Context context;
    private List<NewsReplay> data;
    private ArrayList<ReplayLouZhu> replay_list;
    //    private SharedPreferences sp;
//    private Editor ed;
    private DownLoadUtils downLoadUtils;
    private final String path = "/mnt/sdcard/downimg/";
    private int outHeight, outWidth, height;
    private int width;

    public Value_Adapter(Context context, List<NewsReplay> data) {
        super();
        this.context = context;
        this.data = data;
//        sp = context.getSharedPreferences("text", context.MODE_PRIVATE);
//        ed = sp.edit();
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        width = wm.getDefaultDisplay().getWidth();
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int arg0) {
        return arg0;
    }

    @Override
    public long getItemId(int arg0) {
        return arg0;
    }

    @Override
    public View getView(int arg0, View arg1, ViewGroup arg2) {
        Holder mHolder = null;
        if (arg1 == null) {
            mHolder = new Holder();
            arg1 = View.inflate(context, R.layout.value_listview_item, null);
            mHolder.huifu_photo = (CircleImageView) arg1.findViewById(R.id.huifu_photo);
            mHolder.huifu_name = (TextView) arg1.findViewById(R.id.huifu_name);
            mHolder.huifu_detail = (TextView) arg1.findViewById(R.id.huifu_detail);
            mHolder.huifu_time = (TextView) arg1.findViewById(R.id.huifu_time);
            mHolder.replay_listview = (MyListview) arg1.findViewById(R.id.replay_listview);
            mHolder.huifu_louzhu = (RelativeLayout) arg1.findViewById(R.id.huifu_louzhu);
            mHolder.top_line = (ImageView) arg1.findViewById(R.id.top_line);
            mHolder.button_line = (ImageView) arg1.findViewById(R.id.button_line);
            mHolder.more_shuju = (TextView) arg1.findViewById(R.id.more_shuju);
            mHolder.liearlayout_zan = (LinearLayout) arg1.findViewById(R.id.liearlayout_zan);
            mHolder.content_text_zan = (TextView) arg1.findViewById(R.id.content_text_zan);
            arg1.setTag(mHolder);
        } else {
            mHolder = (Holder) arg1.getTag();
        }

        mHolder.huifu_name.setText(data.get(arg0).getNickname());
        //mHolder.huifu_detail.setText(Html.fromHtml(data.get(arg0).getDetails()));

        //设置图文混排
        setData(mHolder.huifu_detail, data.get(arg0).getDetails());

        Log.i("DetailsDetailsDetails", data.get(arg0).getDetails());

        mHolder.huifu_time.setText((arg0 + 1) + (new StringBuffer("楼").append("  ").append(data.get(arg0).getCreated_at()).toString()));
        ImageLoader.getInstance().displayImage(data.get(arg0).getAvatar(), mHolder.huifu_photo);
        mHolder.content_text_zan.setText(data.get(arg0).getPraise_count() + "");
        JSONArray array = data.get(arg0).getArray();
        String name = data.get(arg0).getNickname();


        if (data.get(arg0).getReplyscount() > 5) {

            mHolder.top_line.setVisibility(View.VISIBLE);
            mHolder.button_line.setVisibility(View.VISIBLE);
            mHolder.more_shuju.setVisibility(View.VISIBLE);

            mHolder.more_shuju.setText(new StringBuffer("查看更多数据").append("    ").append(data.get(arg0).getReplyscount()).toString());
        } else {
            mHolder.top_line.setVisibility(View.GONE);
            mHolder.button_line.setVisibility(View.GONE);
            mHolder.more_shuju.setVisibility(View.GONE);

        }

        replay_list = new ArrayList<ReplayLouZhu>();
        for (int i = 0; i < array.length(); i++) {
            try {
                JSONObject obj = array.getJSONObject(i);

                ReplayLouZhu mReplay = new ReplayLouZhu();
                mReplay.setDetails(obj.getString("details"));
                mReplay.setNickname(obj.getJSONObject("authors").getString("nickname"));
                mReplay.setReplay_pinglunid(obj.getJSONObject("authors").getInt("id"));//回复评论人ID

                mReplay.setReplay_id(obj.getInt("reply_id"));//回复人ID

                mReplay.setCreated_at(obj.getString("created_at"));

                replay_list.add(mReplay);

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
        final int position = arg0;


        if (replay_list.size() > 0) {
            mHolder.replay_listview.setVisibility(View.VISIBLE);
            mHolder.replay_listview.setAdapter(new NewsReplyAdapter(context, replay_list));


        } else {
            mHolder.replay_listview.setVisibility(View.GONE);

        }
        mHolder.more_shuju.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                //	intent.putExtra("reply_id",data.get(position).getReplay_id());
                //	intent.setClass(context, Main_More_PinglunActivity.class);
                context.startActivity(intent);
            }
        });

        mHolder.huifu_louzhu.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                Send_Contant.getInstance().setReply_user(data.get(position).getAuthor());
                Send_Contant.getInstance().setReplay_name(data.get(position).getNickname());
                Send_Contant.getInstance().setReplay_id(data.get(position).getId());
                EventBus.getDefault().postSticky(new Replay_EventBus(2, data.get(position).getNickname()));
//			EventBus.getDefault().post(new Replay_EventBus(2,data.get(position).getNickname()));
            }
        });

        arg1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                //EventBus.getDefault().post(new Replay_EventBus(0,data.get(position).getNickname()));
            }
        });
        final TextView text = mHolder.content_text_zan;
        mHolder.liearlayout_zan.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                //	replay_zan_data(data.get(position).getReplay_id(),text,data.get(position).getPraise_count());
            }
        });
        return arg1;
    }

    class Holder {
        CircleImageView huifu_photo;
        TextView huifu_name;
        TextView huifu_detail;
        TextView huifu_time, content_text_zan;
        MyListview replay_listview;
        RelativeLayout huifu_louzhu;
        ImageView top_line;
        ImageView button_line;
        TextView more_shuju;
        LinearLayout liearlayout_zan;
    }

    public void replay_zan_data(int oid, final TextView textView, final int count) {

        HashMap<String, Object> map = new HashMap<String, Object>();
        if (PreferenceEngine.getInstance().getBoolean(Constant.SP.NAME, Constant.SP.KEY_DENGLU, false)) {
            map.put("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_TOKEN, ""));

        }

        map.put("rid", oid);


        JSONObject params = new JSONObject(map);

        JsonObjectRequest request = new JsonObjectRequest(Method.POST, Contant.add_lianjie,
                params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    Toast.makeText(context, response.getString("msg"), Toast.LENGTH_SHORT).show();
                    if (response.getInt("status") == 1) {
                        int a = count + 1;
                        textView.setText(a + "");
                    }
                } catch (NotFoundException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    private void setData(final TextView tView, final String details) {
        new File(path).mkdirs();
        //初始化下载类
        downLoadUtils = new DownLoadUtils();
        //设置下载类监听事件
        downLoadUtils.setOnDownloadListener(
                new OnDownloadListener() {

                    //下载进度
                    public void onDownloadUpdate(DownLoadUtils manager, int percent) {
                    }

                    //下载失败
                    public void onDownloadError(DownLoadUtils manager, Exception e) {
                    }

                    //开始下载
                    public void onDownloadConnect(DownLoadUtils manager) {
                    }

                    //完成下载
                    public void onDownloadComplete(DownLoadUtils manager, Object result) {
                        //替换sTExt的值，就是把图片的网络路径换成本地SD卡图片路径(最早想法，可以不需要这样做了)
                        //sText.replace(result.toString(), path+String.valueOf(result.hashCode()));
                        //再一次赋值给Textview
                        tView.setText(Html.fromHtml(details, imageGetter, null));
                        Value_Adapter.this.notifyDataSetChanged();
                    }
                }
        );
        //给Textview赋值

        tView.setText(Html.fromHtml(details, imageGetter, null));
    }

    final Html.ImageGetter imageGetter = new Html.ImageGetter() {

        public Drawable getDrawable(String source) {
            Drawable drawable = null;
            String fileString = path + String.valueOf(source.hashCode());

            //判断SD卡里面是否存在图片文件
            if (new File(fileString).exists()) {
                Bitmap bitmap = null;
                //获取本地文件返回Drawable
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;//它仅仅会把它的宽，高取回来给你，这样就不会占用太多的内存

                Bitmap bitmap1 = BitmapFactory.decodeFile(fileString, options);/* 这里返回的bmp是null */

                outHeight = options.outHeight;
                outWidth = options.outWidth;
                //Log.i("wwwwwww", outWidth+"");
                if (outWidth > 200) {
                    /**
                     * 需要在图片不变形的前提下得到宽度为200的缩略图。
                     那么我们需要先计算一下缩放之后，图片的高度是多少
                     */
                    height = options.outHeight * 200 / outWidth;

                    options.inSampleSize = options.outWidth / 200;
                    options.outWidth = 200;
                    options.outHeight = height;
                    options.inJustDecodeBounds = false;
                    bitmap = BitmapFactory.decodeFile(fileString, options);
                    drawable = new BitmapDrawable(bitmap);

                }/*if(outWidth<200&&outWidth>15){
                 *//**
                 * 需要在图片不变形的前提下得到宽度为200的缩略图。
                 那么我们需要先计算一下缩放之后，图片的高度是多少
                 *//*
				height=options.outHeight*15/outWidth;
				
				options.inSampleSize=options.outWidth/15;
				options.outWidth=15;
				options.outHeight=height;
				options.inJustDecodeBounds=false;	
				bitmap=BitmapFactory.decodeFile(fileString, options);
			
			}*/

                else {

                    drawable = Drawable.createFromPath(fileString);
				/*options.inJustDecodeBounds=false;	
				bitmap=BitmapFactory.decodeFile(fileString, options);*/
                }


                /******************加入下面注释的一段会一直在加载*************************/
			/* if(bitmap==null){
				 Log.i("进入进入进入", "进入进入进入");
				 downLoadUtils.download(source, path+String.valueOf(source.hashCode()));
					return drawable;
			 }*/

                //设置图片边界怎么绘制

                if (drawable != null) {
                    // Log.i("widthwidthwidth",drawable.getIntrinsicWidth()+"");
                    if (width < 721) {

                        if (drawable.getIntrinsicWidth() > 200) {
                            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
                        } else if (drawable.getIntrinsicWidth() < 50) {
                            drawable.setBounds(0, 0, drawable.getIntrinsicWidth() * 4, drawable.getIntrinsicHeight() * 4);
                        } else if (drawable.getIntrinsicWidth() < 200 && drawable.getIntrinsicWidth() > 50) {
                            drawable.setBounds(0, 0, drawable.getIntrinsicWidth() * 3, drawable.getIntrinsicHeight() * 3);
                        }
                    } else {
                        if (drawable.getIntrinsicWidth() > 200) {
                            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
                        } else if (drawable.getIntrinsicWidth() < 50) {
                            drawable.setBounds(0, 0, drawable.getIntrinsicWidth() * 7, drawable.getIntrinsicHeight() * 7);
                        } else if (drawable.getIntrinsicWidth() < 200 && drawable.getIntrinsicWidth() > 50) {
                            drawable.setBounds(0, 0, drawable.getIntrinsicWidth() * 4, drawable.getIntrinsicHeight() * 4);
                        }
                    }
                }
                return drawable;
            } else {
                //启动新线程下载
                downLoadUtils.download(source, path + String.valueOf(source.hashCode()));
                return drawable;
            }
        }
    };
}
